{% extends "base.html" %}

{% block title %}实盘交易 - XCQuant{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
        <li class="breadcrumb-item active">实盘交易</li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-rocket me-2"></i>实盘交易
    </h1>
    <div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAccountModal">
            <i class="fas fa-plus me-2"></i>添加账户
        </button>
        <button class="btn btn-success" onclick="refreshAll()">
            <i class="fas fa-sync-alt me-2"></i>刷新
        </button>
    </div>
</div>

<!-- 警告提示 -->
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="fas fa-exclamation-triangle me-2"></i>
    <strong>风险提示：</strong>实盘交易涉及真实资金，请谨慎操作。建议先在模拟环境充分测试策略。
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>

<!-- 账户概览 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            总资产 (USDT)
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalBalance">--</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            今日盈亏
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="todayPnl">--</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-chart-line fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            运行策略
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="runningStrategies">--</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-cogs fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            活跃订单
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="activeOrders">--</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-list-alt fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 主要内容区域 -->
<div class="row">
    <!-- 账户管理 -->
    <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-user-circle me-2"></i>交易账户
                </h6>
            </div>
            <div class="card-body">
                <div id="accountsList">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>加载中...
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 快速操作 -->
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="startAllLiveStrategies()">
                        <i class="fas fa-play me-1"></i>启动所有策略
                    </button>
                    <button class="btn btn-outline-warning btn-sm" onclick="stopAllLiveStrategies()">
                        <i class="fas fa-stop me-1"></i>停止所有策略
                    </button>
                    <button class="btn btn-outline-danger btn-sm" onclick="emergencyStop()">
                        <i class="fas fa-exclamation-triangle me-1"></i>紧急停止
                    </button>
                    <button class="btn btn-outline-info btn-sm" onclick="exportTradingData()">
                        <i class="fas fa-download me-1"></i>导出数据
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 实盘策略 -->
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-rocket me-2"></i>实盘策略
                </h6>
                <button class="btn btn-sm btn-primary" onclick="deployStrategy()">
                    <i class="fas fa-plus me-1"></i>部署策略
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="liveStrategiesTable">
                        <thead>
                            <tr>
                                <th>策略名称</th>
                                <th>账户</th>
                                <th>交易对</th>
                                <th>状态</th>
                                <th>今日盈亏</th>
                                <th>总盈亏</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="liveStrategiesBody">
                            <tr>
                                <td colspan="7" class="text-center text-muted">
                                    <i class="fas fa-spinner fa-spin me-2"></i>加载中...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- 实时订单 -->
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-list-alt me-2"></i>实时订单
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>策略</th>
                                <th>交易对</th>
                                <th>方向</th>
                                <th>价格</th>
                                <th>数量</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="ordersBody">
                            <tr>
                                <td colspan="8" class="text-center text-muted">暂无订单</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加账户模态框 -->
<div class="modal fade" id="addAccountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus me-2"></i>添加交易账户
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addAccountForm">
                    <div class="form-group mb-3">
                        <label for="accountName">账户名称 *</label>
                        <input type="text" class="form-control" id="accountName" name="name" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="accountExchange">交易所 *</label>
                        <select class="form-control" id="accountExchange" name="exchange" required>
                            <option value="">请选择</option>
                            <option value="okx">OKX</option>
                            <option value="binance">Binance</option>
                        </select>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="accountType">账户类型 *</label>
                        <select class="form-control" id="accountType" name="account_type" required>
                            <option value="">请选择</option>
                            <option value="spot">现货账户</option>
                            <option value="futures">合约账户</option>
                        </select>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="apiKey">API Key *</label>
                        <input type="text" class="form-control" id="apiKey" name="api_key" required>
                        <small class="form-text text-muted">请确保API Key有交易权限</small>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="secretKey">Secret Key *</label>
                        <input type="password" class="form-control" id="secretKey" name="secret_key" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="passphrase">Passphrase</label>
                        <input type="password" class="form-control" id="passphrase" name="passphrase">
                        <small class="form-text text-muted">OKX需要填写</small>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="sandbox">环境</label>
                        <select class="form-control" id="sandbox" name="sandbox">
                            <option value="false">正式环境</option>
                            <option value="true">沙盒环境</option>
                        </select>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="testConnection" checked>
                        <label class="form-check-label" for="testConnection">
                            添加前测试连接
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addAccount()">添加账户</button>
            </div>
        </div>
    </div>
</div>

<!-- 部署策略模态框 -->
<div class="modal fade" id="deployStrategyModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-rocket me-2"></i>部署实盘策略
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="deployStrategyForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="deployAccount">选择账户 *</label>
                                <select class="form-control" id="deployAccount" name="account_id" required>
                                    <option value="">请选择账户</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="deployStrategy">选择策略 *</label>
                                <select class="form-control" id="deployStrategy" name="strategy_id" required>
                                    <option value="">请选择策略</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="deployAmount">投入资金 (USDT) *</label>
                                <input type="number" class="form-control" id="deployAmount" name="amount" 
                                       step="0.01" min="1" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="deployRiskLevel">风险等级</label>
                                <select class="form-control" id="deployRiskLevel" name="risk_level">
                                    <option value="low">低风险</option>
                                    <option value="medium" selected>中风险</option>
                                    <option value="high">高风险</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="deployNotes">备注</label>
                        <textarea class="form-control" id="deployNotes" name="notes" rows="3"></textarea>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>提示：</strong>部署前请确保账户余额充足，策略将立即开始执行。
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDeploy()">确认部署</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // 初始化页面
    loadAccounts();
    loadLiveStrategies();
    loadOverviewData();
    loadOrders();
    
    // 定时刷新
    setInterval(function() {
        loadOverviewData();
        loadOrders();
    }, 5000);
});

// 加载账户列表
function loadAccounts() {
    $.ajax({
        url: '/api/accounts',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateAccountsList(response.data);
                updateAccountOptions(response.data);
            }
        },
        error: function() {
            $('#accountsList').html('<div class="text-center text-danger">加载失败</div>');
        }
    });
}

// 更新账户列表
function updateAccountsList(accounts) {
    const container = $('#accountsList');
    container.empty();
    
    if (accounts.length === 0) {
        container.html('<div class="text-center text-muted">暂无账户</div>');
        return;
    }
    
    accounts.forEach(function(account) {
        const statusClass = account.status === 'connected' ? 'success' : 'danger';
        const balanceClass = account.balance >= 0 ? 'text-success' : 'text-danger';
        
        const accountCard = `
            <div class="card mb-2">
                <div class="card-body p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-1">${account.name}</h6>
                            <small class="text-muted">${account.exchange} - ${account.account_type}</small>
                        </div>
                        <div class="text-end">
                            <span class="badge bg-${statusClass}">${account.status}</span>
                        </div>
                    </div>
                    <div class="mt-2">
                        <div class="small text-gray-500">余额</div>
                        <div class="h6 mb-0 ${balanceClass}">${account.balance} USDT</div>
                    </div>
                    <div class="mt-2">
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="testConnection('${account.id}')">
                            <i class="fas fa-plug"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-info me-1" onclick="viewAccount('${account.id}')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteAccount('${account.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        container.append(accountCard);
    });
}

// 更新账户选项
function updateAccountOptions(accounts) {
    const select = $('#deployAccount');
    select.empty().append('<option value="">请选择账户</option>');
    
    accounts.forEach(function(account) {
        if (account.status === 'connected') {
            select.append(`<option value="${account.id}">${account.name} (${account.exchange})</option>`);
        }
    });
}

// 加载实盘策略
function loadLiveStrategies() {
    $.ajax({
        url: '/api/live-strategies',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateLiveStrategiesTable(response.data);
            }
        },
        error: function() {
            $('#liveStrategiesBody').html('<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>');
        }
    });
}

// 更新实盘策略表格
function updateLiveStrategiesTable(strategies) {
    const tbody = $('#liveStrategiesBody');
    tbody.empty();
    
    if (strategies.length === 0) {
        tbody.html('<tr><td colspan="7" class="text-center text-muted">暂无实盘策略</td></tr>');
        return;
    }
    
    strategies.forEach(function(strategy) {
        const statusBadge = getStatusBadge(strategy.status);
        const todayPnlClass = strategy.today_pnl >= 0 ? 'text-success' : 'text-danger';
        const totalPnlClass = strategy.total_pnl >= 0 ? 'text-success' : 'text-danger';
        
        const row = `
            <tr>
                <td>${strategy.name}</td>
                <td>${strategy.account_name}</td>
                <td>${strategy.symbol}</td>
                <td>${statusBadge}</td>
                <td class="${todayPnlClass}">${strategy.today_pnl} USDT</td>
                <td class="${totalPnlClass}">${strategy.total_pnl} USDT</td>
                <td>
                    <div class="btn-group" role="group">
                        <button class="btn btn-sm btn-outline-primary" onclick="viewLiveStrategy('${strategy.id}')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-success" onclick="startLiveStrategy('${strategy.id}')">
                            <i class="fas fa-play"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-warning" onclick="stopLiveStrategy('${strategy.id}')">
                            <i class="fas fa-stop"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteLiveStrategy('${strategy.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 加载概览数据
function loadOverviewData() {
    $.ajax({
        url: '/api/live-trading/overview',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const data = response.data;
                $('#totalBalance').text(data.total_balance + ' USDT');
                
                const todayPnlClass = data.today_pnl >= 0 ? 'text-success' : 'text-danger';
                $('#todayPnl').removeClass('text-success text-danger').addClass(todayPnlClass)
                    .text(data.today_pnl + ' USDT');
                
                $('#runningStrategies').text(data.running_strategies);
                $('#activeOrders').text(data.active_orders);
            }
        }
    });
}

// 加载订单
function loadOrders() {
    $.ajax({
        url: '/api/orders',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateOrdersTable(response.data);
            }
        }
    });
}

// 更新订单表格
function updateOrdersTable(orders) {
    const tbody = $('#ordersBody');
    tbody.empty();
    
    if (orders.length === 0) {
        tbody.html('<tr><td colspan="8" class="text-center text-muted">暂无订单</td></tr>');
        return;
    }
    
    orders.slice(0, 10).forEach(function(order) {
        const sideBadge = order.side === 'buy' ? 
            '<span class="badge bg-success">买入</span>' : 
            '<span class="badge bg-danger">卖出</span>';
        const statusBadge = getOrderStatusBadge(order.status);
        
        const row = `
            <tr>
                <td>${order.timestamp}</td>
                <td>${order.strategy_name}</td>
                <td>${order.symbol}</td>
                <td>${sideBadge}</td>
                <td>${order.price}</td>
                <td>${order.quantity}</td>
                <td>${statusBadge}</td>
                <td>
                    <button class="btn btn-sm btn-outline-danger" onclick="cancelOrder('${order.id}')">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 获取订单状态徽章
function getOrderStatusBadge(status) {
    const badges = {
        'pending': '<span class="badge bg-warning">待成交</span>',
        'filled': '<span class="badge bg-success">已成交</span>',
        'cancelled': '<span class="badge bg-secondary">已取消</span>',
        'failed': '<span class="badge bg-danger">失败</span>'
    };
    return badges[status] || '<span class="badge bg-secondary">未知</span>';
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'running': '<span class="badge bg-success">运行中</span>',
        'stopped': '<span class="badge bg-danger">已停止</span>',
        'paused': '<span class="badge bg-warning">已暂停</span>',
        'error': '<span class="badge bg-danger">错误</span>'
    };
    return badges[status] || '<span class="badge bg-secondary">未知</span>';
}

// 添加账户
function addAccount() {
    const formData = {
        name: $('#accountName').val(),
        exchange: $('#accountExchange').val(),
        account_type: $('#accountType').val(),
        api_key: $('#apiKey').val(),
        secret_key: $('#secretKey').val(),
        passphrase: $('#passphrase').val(),
        sandbox: $('#sandbox').val() === 'true',
        test_connection: $('#testConnection').is(':checked')
    };
    
    if (!formData.name || !formData.exchange || !formData.account_type || 
        !formData.api_key || !formData.secret_key) {
        alert('请填写必填字段');
        return;
    }
    
    $.ajax({
        url: '/api/accounts',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                $('#addAccountModal').modal('hide');
                loadAccounts();
                alert('账户添加成功！');
            } else {
                alert('添加失败: ' + response.message);
            }
        },
        error: function() {
            alert('添加失败');
        }
    });
}

// 部署策略
function deployStrategy() {
    // 加载可用策略
    $.ajax({
        url: '/api/strategies',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const select = $('#deployStrategy');
                select.empty().append('<option value="">请选择策略</option>');
                
                response.data.forEach(function(strategy) {
                    select.append(`<option value="${strategy.id}">${strategy.name} (${strategy.type})</option>`);
                });
                
                $('#deployStrategyModal').modal('show');
            }
        }
    });
}

// 确认部署
function confirmDeploy() {
    const formData = {
        account_id: $('#deployAccount').val(),
        strategy_id: $('#deployStrategy').val(),
        amount: parseFloat($('#deployAmount').val()),
        risk_level: $('#deployRiskLevel').val(),
        notes: $('#deployNotes').val()
    };
    
    if (!formData.account_id || !formData.strategy_id || !formData.amount) {
        alert('请填写必填字段');
        return;
    }
    
    if (formData.amount <= 0) {
        alert('投入资金必须大于0');
        return;
    }
    
    if (confirm('确定要部署这个策略到实盘吗？这将使用真实资金进行交易。')) {
        $.ajax({
            url: '/api/live-strategies',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    $('#deployStrategyModal').modal('hide');
                    loadLiveStrategies();
                    loadOverviewData();
                    alert('策略部署成功！');
                } else {
                    alert('部署失败: ' + response.message);
                }
            },
            error: function() {
                alert('部署失败');
            }
        });
    }
}

// 其他操作函数
function testConnection(accountId) {
    $.ajax({
        url: '/api/accounts/' + accountId + '/test',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                alert('连接测试成功');
                loadAccounts();
            } else {
                alert('连接失败: ' + response.message);
            }
        }
    });
}

function viewAccount(accountId) {
    window.open('/accounts/' + accountId, '_blank');
}

function deleteAccount(accountId) {
    if (confirm('确定要删除这个账户吗？')) {
        $.ajax({
            url: '/api/accounts/' + accountId,
            method: 'DELETE',
            success: function(response) {
                if (response.success) {
                    loadAccounts();
                    alert('账户删除成功');
                } else {
                    alert('删除失败: ' + response.message);
                }
            }
        });
    }
}

function startLiveStrategy(strategyId) {
    $.ajax({
        url: '/api/live-strategies/' + strategyId + '/start',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                loadLiveStrategies();
                alert('策略启动成功');
            } else {
                alert('启动失败: ' + response.message);
            }
        }
    });
}

function stopLiveStrategy(strategyId) {
    if (confirm('确定要停止这个实盘策略吗？')) {
        $.ajax({
            url: '/api/live-strategies/' + strategyId + '/stop',
            method: 'POST',
            success: function(response) {
                if (response.success) {
                    loadLiveStrategies();
                    alert('策略停止成功');
                } else {
                    alert('停止失败: ' + response.message);
                }
            }
        });
    }
}

function deleteLiveStrategy(strategyId) {
    if (confirm('确定要删除这个实盘策略吗？这将停止所有相关交易。')) {
        $.ajax({
            url: '/api/live-strategies/' + strategyId,
            method: 'DELETE',
            success: function(response) {
                if (response.success) {
                    loadLiveStrategies();
                    loadOverviewData();
                    alert('策略删除成功');
                } else {
                    alert('删除失败: ' + response.message);
                }
            }
        });
    }
}

function cancelOrder(orderId) {
    if (confirm('确定要取消这个订单吗？')) {
        $.ajax({
            url: '/api/orders/' + orderId + '/cancel',
            method: 'POST',
            success: function(response) {
                if (response.success) {
                    loadOrders();
                    alert('订单取消成功');
                } else {
                    alert('取消失败: ' + response.message);
                }
            }
        });
    }
}

function emergencyStop() {
    if (confirm('确定要紧急停止所有策略和订单吗？这是不可逆操作！')) {
        $.ajax({
            url: '/api/live-trading/emergency-stop',
            method: 'POST',
            success: function(response) {
                if (response.success) {
                    loadLiveStrategies();
                    loadOrders();
                    loadOverviewData();
                    alert('紧急停止执行完成');
                } else {
                    alert('紧急停止失败: ' + response.message);
                }
            }
        });
    }
}

function refreshAll() {
    loadAccounts();
    loadLiveStrategies();
    loadOverviewData();
    loadOrders();
}

function exportTradingData() {
    window.open('/api/live-trading/export', '_blank');
}

function startAllLiveStrategies() {
    if (confirm('确定要启动所有实盘策略吗？')) {
        $.ajax({
            url: '/api/live-strategies/start-all',
            method: 'POST',
            success: function(response) {
                loadLiveStrategies();
                alert('批量启动完成');
            }
        });
    }
}

function stopAllLiveStrategies() {
    if (confirm('确定要停止所有实盘策略吗？')) {
        $.ajax({
            url: '/api/live-strategies/stop-all',
            method: 'POST',
            success: function(response) {
                loadLiveStrategies();
                alert('批量停止完成');
            }
        });
    }
}
</script>
{% endblock %}